import React, {useState, useEffect, useRef} from 'react'
import './index.less'

const Tabs = (props) => {
  const { items } = props
  const [currentTab, setCurrentTab] = useState(items[0].key)

  const isFirstRender = useRef(true);

  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
      return;
    }
    props.onChange && props.onChange(currentTab)
  }, [currentTab])

  return (
    <>
      <div className="tabs">
        <div className="tabs-nav">
          <ul className="tabs-nav-list">
            {
              items.map(item => <li className={`tabs-nav-item ${currentTab === item.key ? 'tabs-nav-item-active' : ''}`} onClick={() => setCurrentTab(item.key)} key={item.key}>{item.label}</li>)
            }
          </ul>
          <div className="tabs-nav-line" style={{width: `${100 / items.length}%`, position: 'relative', left: `${100 / items.length * items.findIndex(item => item.key === currentTab)}%`}}></div>
        </div>
        <div className="tabs-main">
          <div className="tabs-main-wrap" style={{
            width: `${100 * items.length}%`,
            transform: `translateX(-${100 * (items.findIndex(item => item.key === currentTab)) / items.length}%)`
          }}>
            {
              items.map(item => (
                <div className={`tabs-content ${currentTab === item.key ? 'tabs-content-active' : ''}`} key={item.key}>
                  {currentTab === item.key && item.node}
                </div>
              ))
            }
          </div>
        </div>
      </div>
    </>
  )
}

export default Tabs;